package com.customization.unionpay.market.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.service.MarketingProjectInfoService;
import com.customization.unionpay.market.util.ClearFundButtonRelated;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import com.engine.core.impl.Service;
import com.engine.cube.biz.ShardingActionHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class MarketingProjectInfoServiceImpl extends Service implements MarketingProjectInfoService {

    private static final Logger log = LoggerFactory.getLogger(MarketingProjectInfoServiceImpl.class);

    @Override
    public synchronized boolean addProjectInfo(String projectCode, String projectName, String organizer, String sponsor, String project, String scene,String payPersonalTax,String personalTaxAt,String contributionType, String unionpayCtbtAt, String extCtbtAt, String partnerType, String partnerName) throws Exception {

        // organizer,sponsor
        RecordSetTrans rst = new RecordSetTrans();

        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 营销项目信息台账表单id
        int formId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_project_info_form_id"));
        // 营销项目信息台账模块id
        int formmodeId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_project_info_formmode_id"));

        // 获取营销项目信息台账主表表名
        String maintablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
        log.info("获取营销项目信息台账主表表名："+maintablename);
        // 先调用内部方法新建一条数据，获取数据id
        int billid = com.customization.unionpay.market.util.FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {

            log.info("organizer："+organizer);

            Boolean companyOrDepartment = com.customization.unionpay.market.util.FormDataUtils.isCompanyOrDepartment(organizer);
            log.info("companyOrDepartment："+companyOrDepartment);
            log.info("sponsor："+sponsor);

            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 是否缴纳个税  1-有发票，标记“否” 2-部分有发票，3-无发票时，时标记“是”
            log.info("payPersonalTax："+payPersonalTax);
            String isTax = "";
            if(!"".equals(payPersonalTax)) {
                if ("1".equals(payPersonalTax)) {
                    isTax = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "sfjngs", "否");
                    if (StrUtil.isBlank(isTax)) {
                        log.error("是否缴纳个税枚举:否,为空或找不到！");
                    }
                } else {
                    isTax = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "sfjngs", "是");
                    if (StrUtil.isBlank(isTax)) {
                        log.error("是否缴纳个税枚举:是,为空或找不到！");
                    }
                }
            }

            // 填写“待缴个税金额” 金额为空
            log.info("personalTaxAt："+personalTaxAt);
            String tax = "";
            if(!"待缴个税金额".equals(personalTaxAt)){
                // 万元转元
                tax =  com.customization.unionpay.market.util.FormDataUtils.changeWanYuanToYuan(personalTaxAt);
                log.info("个税:"+tax);
            }else {
                tax = "0";
            }
            // 万元转元
            String unionpayCtbtAtYuan = com.customization.unionpay.market.util.FormDataUtils.changeWanYuanToYuan(unionpayCtbtAt);
            log.info("银联出资金额:"+unionpayCtbtAtYuan);
            // 万元转元
            String extCtbtAtYuan = com.customization.unionpay.market.util.FormDataUtils.changeWanYuanToYuan(extCtbtAt);
            log.info("外部出资金额:"+extCtbtAtYuan);

            // 根据当前信息使用id修改新建数据
            StringBuilder updateSql = new StringBuilder( "update ");
            updateSql.append(maintablename);
            updateSql.append(" set ");
            updateSql.append(" PROJECT_CODE='");
            updateSql.append(projectCode);
            updateSql.append("',");

            updateSql.append(" PROJECT_NAME='");
            updateSql.append(projectName);
            updateSql.append("',");

            if(companyOrDepartment){
                String idByCompanyCode = com.customization.unionpay.market.util.FormDataUtils.getIdByCompanyCode(organizer);
                updateSql.append(" zbdw='");
                updateSql.append(idByCompanyCode);
                updateSql.append("',");
            }else {
                JSONObject infoByDepartmentCode = com.customization.unionpay.market.util.FormDataUtils.getInfoByDepartmentCode(organizer);
                String idByCompanyCode = infoByDepartmentCode.getString("subCompanyId");
                String idByDepartCode = infoByDepartmentCode.getString("id");

                updateSql.append(" zbdw='");
                updateSql.append(idByCompanyCode);
                updateSql.append("',");

                updateSql.append(" zbbm='");
                updateSql.append(idByDepartCode);
                updateSql.append("',");
            }

            updateSql.append(" zbr='");
            updateSql.append(sponsor);
            updateSql.append("',");

            updateSql.append(" cp='");
            updateSql.append(project);
            updateSql.append("',");

            updateSql.append(" cj='");
            updateSql.append(scene);
            updateSql.append("',");
            if(isTax != null && !"".equals(isTax) ) {
                updateSql.append(" sfjngs='");
                updateSql.append(isTax);
                updateSql.append("',");
            }
            updateSql.append(" gsje='");
            updateSql.append(tax);
            updateSql.append("',");

            updateSql.append(" czfs='");
            updateSql.append(contributionType);
            updateSql.append("',");

            updateSql.append(" ylczje='");
            updateSql.append(unionpayCtbtAtYuan);
            updateSql.append("',");

            updateSql.append(" wbczje='");
            updateSql.append(extCtbtAtYuan);
            updateSql.append("',");

            updateSql.append(" hzflx='");
            updateSql.append(partnerType);
            updateSql.append("',");

            updateSql.append(" hzfmc='");
            updateSql.append(partnerName);
            updateSql.append("',");

            updateSql.append(" form_biz_id='");
            updateSql.append(formBizId);
            updateSql.append("' ");

            updateSql.append(" where id = '");
            updateSql.append(billid);
            updateSql.append("'");

            log.info("查询sql:"+updateSql);
            rst.executeUpdate(updateSql.toString());
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(user.getUID(), formmodeId, billid);
            return true;
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            ClearFundButtonRelated.deleteByBillId(maintablename, billid);
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public JSONObject getProjectInfo(String projectCode) throws Exception {

        RecordSet rs = new RecordSet();

        try {
            // 营销项目信息台账表单id
            int formId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_project_info_form_id"));

            // 营销活动事项台账表单id
            int ledgerFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));

            // 营销预付活动台账表单id
            int marketingPrepaidActivityLedgerFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_prepaid_activity_ledger_form_id"));

            // 营销项目流水明细表表单id
            int marketingProjectFlowDetailsTableFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_project_flow_details_table_form_id"));

            // 获取营销项目信息台账主表表名
            String maintablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
            log.info("查询maintablename:"+maintablename);

            // 获取营销项目信息台账主表表名
            String marketingProjectFlowDetailsTablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(marketingProjectFlowDetailsTableFormId);
            log.info("查询marketingProjectFlowDetailsTablename:"+marketingProjectFlowDetailsTablename);

            //  ISCLOSE	           项目是否可关闭
            boolean finshByMarketingActivityLedger = isFinshByMarketingActivityLedger(ledgerFormId, projectCode);
            boolean finshByPrepaidActivityLedger = isFinshByPrepaidActivityLedger(marketingPrepaidActivityLedgerFormId, projectCode);

            String sql = "select PROJECT_CODE, PROJECT_NAME, zbdw as ORGANIZER, zbbm as zbbm, xmkssj as PRO_START_TM, zbr as SPONSOR, cp as PROJECT, cj as SCENE, hdxs as ACTIVITIES, sfjngs as PAY_PERSONAL_TAX, gsje as PERSONAL_TAX_AT, czfs as CONTRIBUTION_TYPE, ylczje as UNIONPAY_CTBT_AT, wbczje as EXT_CTBT_AT, hzflx as PARTNER_TYPE, hzfmc as PARTNER_NAME from #{tableName} where PROJECT_CODE = ? ";
            sql = sql.replace("#{tableName}",maintablename);
            log.info("查询sql:"+sql);
            rs.executeQuery(sql,projectCode);

            JSONObject result = new JSONObject();
            if (rs.next()) {
                //  PROJECT_CODE	    项目编号                                         PROJECT_CODE
                String PROJECT_CODE = Util.null2String(rs.getString("PROJECT_CODE"));
                //  PROJECT_NAME	    项目名称                                         PROJECT_NAME
                String PROJECT_NAME = Util.null2String(rs.getString("PROJECT_NAME"));
                //　ORGANIZER	        主办单位                                         zbdw
                String ORGANIZER = Util.null2String(rs.getString("ORGANIZER"));

                String zbbm = Util.null2String(rs.getString("zbbm"));

                //　PRO_START_TM	    项目开始时间(yyyy-MM-dd)                          xmkssj
                String PRO_START_TM = Util.null2String(rs.getString("PRO_START_TM"));
                //  SPONSOR	            主办人                                           zbr
                String SPONSOR = Util.null2String(rs.getString("SPONSOR"));
                //　PROJECT	            产品                                             cp
                String PROJECT = Util.null2String(rs.getString("PROJECT"));
                //　SCENE	            场景                                             cj
                String SCENE = Util.null2String(rs.getString("SCENE"));
                //　PAY_PERSONAL_TAX	是否缴纳个税      下拉框                                sfjngs
                String PAY_PERSONAL_TAX = Util.null2String(rs.getString("PAY_PERSONAL_TAX"));
                //　PERSONAL_TAX_AT	    个税金额                                              gsje
                String PERSONAL_TAX_AT = Util.null2String(rs.getString("PERSONAL_TAX_AT"));
                //  CONTRIBUTION_TYPE	出资方式(1.内部出资，2-外部出资，3-内外部联合出资)  下拉框     czfs
                String CONTRIBUTION_TYPE = Util.null2String(rs.getString("CONTRIBUTION_TYPE"));
                //　UNIONPAY_CTBT_AT	银联出资金额                                          ylczje
                String UNIONPAY_CTBT_AT = Util.null2String(rs.getString("UNIONPAY_CTBT_AT"));
                //　EXT_CTBT_AT	        外部出资金额        下拉框                              wbczje
                String EXT_CTBT_AT =  Util.null2String(rs.getString("EXT_CTBT_AT"));
                //　PARTNER_TYPE	    合作方类型                                        hzflx
                String PARTNER_TYPE = Util.null2String(rs.getString("PARTNER_TYPE"));
                //　PARTNER_NAME	    合作方名称                                        hzfmc
                String PARTNER_NAME = Util.null2String(rs.getString("PARTNER_NAME"));

                result.put("PROJECT_CODE", PROJECT_CODE);
                result.put("PROJECT_NAME", PROJECT_NAME);
                result.put("PRO_START_TM", PRO_START_TM);
                log.info("ORGANIZER:"+ORGANIZER);
                log.info("zbbm:"+zbbm);
                log.info("SPONSOR:"+SPONSOR);
                if(!"".equals(zbbm)){
                    result.put("ORGANIZER",  com.customization.unionpay.market.util.FormDataUtils.getCompanyCodeById(ORGANIZER));
                }else {
                    result.put("ORGANIZER", com.customization.unionpay.market.util.FormDataUtils.getDepartmentCodeById(zbbm));
                }
                result.put("SPONSOR", com.customization.unionpay.market.util.FormDataUtils.getResourceCodeByResourceLoginId(SPONSOR));
                result.put("PROJECT", PROJECT);
                result.put("SCENE", SCENE);
                result.put("PAY_PERSONAL_TAX", PAY_PERSONAL_TAX);
                result.put("PERSONAL_TAX_AT", PERSONAL_TAX_AT);
                result.put("CONTRIBUTION_TYPE", CONTRIBUTION_TYPE);
                result.put("UNIONPAY_CTBT_AT", UNIONPAY_CTBT_AT);
                result.put("EXT_CTBT_AT", EXT_CTBT_AT);
                result.put("PARTNER_TYPE", PARTNER_TYPE);
                result.put("PARTNER_NAME", PARTNER_NAME);
                if(finshByMarketingActivityLedger && finshByPrepaidActivityLedger){
                    result.put("ISCLOSE", true);
                }else {
                    result.put("ISCLOSE", false);
                }

                StringBuilder dTsql = new StringBuilder("select djbh,djlx,djje,zpse from ");
                dTsql.append(marketingProjectFlowDetailsTablename);
                dTsql.append(" where PROJECT_CODE = '");
                dTsql.append(projectCode);
                dTsql.append("' ");
                log.info("查询dTsql:"+dTsql.toString());
                rs.executeQuery(dTsql.toString());

                List<JSONObject> resultDts = new ArrayList<>();
                while (rs.next()) {
                    String djlx = Util.null2String(rs.getString("djlx"));
                    JSONObject resultDt = new JSONObject();
                    // 单据编号  djbh                 DOC_CODE
                    resultDt.put("DOC_CODE", Util.null2String(rs.getString("djbh")));
                    // 单据金额  djje                 DOC_AT
                    resultDt.put("DOC_AT", Util.null2String(rs.getString("djje")));
                    // 专票税额  zpse                 SPECIAL_INV_TAX_AT
                    resultDt.put("SPECIAL_INV_TAX_AT", Util.null2String(rs.getString("zpse")));
                    // 单据类型  djlx                 DOC_TYPE
                    resultDt.put("DOC_TYPE", !"".equals(djlx) ? com.customization.unionpay.market.util.FormDataUtils.getItemName(marketingProjectFlowDetailsTableFormId, "djlx", djlx) : "");
                    resultDts.add(resultDt);
                }

                result.put("DETAILS", resultDts);
                return result;
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 营销活动事项台账财务是否结束
     * @param ledgerFormId
     * @param projectCode
     * @return
     * @throws Exception
     */
    private boolean isFinshByMarketingActivityLedger(int ledgerFormId,String projectCode) throws Exception {
        boolean res = true;
        RecordSet rs = new RecordSet();
        try {
            String isNot = com.customization.unionpay.market.util.FormDataUtils.getItemValue(ledgerFormId, "cwsfjs", "否");
            log.info("财务是否结束：" + isNot);
            String maintablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
            log.info("maintablename："+maintablename);

            String sql = "select count(id) as num from #{tableName} where PROJECT_CODE = ? ";
            sql = sql.replace("#{tableName}",maintablename);
            log.info("查询sql:"+sql);
            rs.executeQuery(sql,projectCode);
            if (rs.next()) {
                int num = rs.getInt("num");
                log.info("num:"+num);
                if(num > 0){
                    sql = "select id from #{tableName} where PROJECT_CODE = ? and cwsfjs = ? ";
                    sql = sql.replace("#{tableName}",maintablename);
                    log.info("查询sql:"+sql);
                    rs.executeQuery(sql,projectCode,isNot);
                    if (rs.next()) {
                        res = false;
                    }
                }else {
                    res = false;
                }
            }else {
                res = false;
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return res;
    }

    /**
     * 营销预付活动事项台账财务是否结束
     * @param marketingPrepaidActivityLedgerFormId
     * @param projectCode
     * @return
     * @throws Exception
     */
    private boolean isFinshByPrepaidActivityLedger(int marketingPrepaidActivityLedgerFormId,String projectCode) throws Exception {
        boolean res = true;
        RecordSet rs = new RecordSet();
        try {
            String isNot = com.customization.unionpay.market.util.FormDataUtils.getItemValue(marketingPrepaidActivityLedgerFormId, "cwsfjs", "否");
            log.info("财务是否结束：" + isNot);
            String maintablename = FormDataUtils.getTableName(marketingPrepaidActivityLedgerFormId);
            log.info("maintablename："+maintablename);

            String sql = "select count(id) as num from #{tableName} where PROJECT_CODE = ? ";
            sql = sql.replace("#{tableName}",maintablename);
            log.info("查询sql:"+sql);
            rs.executeQuery(sql,projectCode);
            if (rs.next()) {
                int num = rs.getInt("num");
                log.info("num:"+num);
                if(num > 0){
                    sql = "select id  from #{tableName} where PROJECT_CODE = ? and cwsfjs = ? ";
                    sql = sql.replace("#{tableName}",maintablename);
                    log.info("查询sql:"+sql);
                    rs.executeQuery(sql,projectCode,isNot);
                    if (rs.next()) {
                        res = false;
                    }
                }else {
                    res = false;
                }
            }else {
                res = false;
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return res;
    }

}
